package com.shinewind.gateway.filter;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.shinewind.gateway.result.Result;
import com.shinewind.gateway.util.JwtTemplate;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;

@Component
@Slf4j
public class MyUserGlobalFilter implements GlobalFilter, Ordered {
    @Autowired
    private JwtTemplate jwtTemplate;
    private static final String [] whiteApi={
            "/index/model/**","/modelEvaluating/**","/index/search/**",
            "/userInfo/username","/userInfo/*","/userInfo/detail/*","/sso/**"
    };

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //写业务逻辑
        String token = exchange.getRequest().getHeaders().getFirst("Authorization");
        String requestUrl = exchange.getRequest().getURI().getPath();
        AntPathMatcher antPathMatcher = new AntPathMatcher();
        //没有token,只能放行访问白名单里的api
        if(StringUtils.isBlank(token)){
            for(String url:whiteApi){
                System.out.println("requestUrl:"+requestUrl);
                System.out.println("white:"+url);
                System.out.println("Boolean:"+antPathMatcher.match(url,requestUrl));
                //匹配到白名单，放行
                if(antPathMatcher.match(url,requestUrl)){
                    return chain.filter(exchange);
                }
            }
            //没有匹配到白名单
            /*exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
            return exchange.getResponse().setComplete();*/
            return buildDataBufferAndWriteResponse(exchange.getResponse(),
                    Result.error(HttpStatus.UNAUTHORIZED.value(),false,"没有访问权限"));
        }
        //有token
        else{
            /*//验证token
            if(jwtTemplate.ValidateToken(token)){
                return chain.filter(exchange);
            }
            else{
                exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
                return exchange.getResponse().setComplete();
            }*/
            Claims claims  = jwtTemplate.parseJwt(token);
            List<String> authorities = (List<String>) claims.get("rol");
            System.out.println("rolList:"+authorities);
            System.out.println("bool:"+(authorities.indexOf("ROLE_ADMIN")));;
            System.out.println("rol"+claims.get("rol"));
            return chain.filter(exchange);
        }
    }

    //数字越小，优先级越高
    @Override
    public int getOrder() {
        return 0;
    }

    private Mono<Void> buildDataBufferAndWriteResponse(ServerHttpResponse resp, Result result) {
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            resp.getHeaders().add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
            byte[] data = objectMapper.writeValueAsBytes(result);
            DataBuffer buffer = resp.bufferFactory().wrap(data);
            return resp.writeWith(Mono.just(buffer));
        } catch (JsonProcessingException e) {
            log.error("Json process occur error ,info={}", e.getMessage(), e);
        }
        return null;
    }
}
